package com.CGFrame.struts;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.Filter;
import java.io.*;
import java.util.*;

public class LoginFilter implements Filter {

	private FilterConfig filterConfig = null;
	
	String loginPage = null;
	//Initialize global variables
	public void init(FilterConfig filterConfig) throws ServletException {
		loginPage = "/welcome.jsp";
		this.filterConfig = filterConfig;
	}
	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
        HttpServletRequest req = (HttpServletRequest) request;
  //      HttpServletResponse res = (HttpServletResponse) response;

        HttpSession session = req.getSession();
   //     if ( session==null) System.out.println("Session Null");
     //   try {
        	
        	String currentpage = req.getRequestURI();
        	if (currentpage.endsWith("login.do"))
        	{
        		chain.doFilter(request, response);
        		return;
        	}
        	Random random = new Random();
        	
        	//business logic
        	if (session==null || (session.getAttribute("RegUserID") == null)) {        		
        		//res.sendRedirect(loginPage);
        		filterConfig.getServletContext().getRequestDispatcher(loginPage).forward(request, response);

        		return;
        	}

        	
        	chain.doFilter( request, response );   
        	return;
        	
     //   }
        	
    //    catch (Exception e) {
    //      e.printStackTrace();
     //   }

	}


}
